<template>
  <c-dialog v-if="dialogFlag" v-model:show="dialogFlag" :title="title" :width="500" @confirm="save" @close="close">
    <el-form ref="ruleFormRef" :rules="rules" :model="formdata" class="newFormStyle" label-width="100px">
      <br>
      <!-- <el-form-item label="类型" prop="roleType">
                <div class="mybd">
                    <el-radio-group v-model="formdata.roleType">
                        <el-radio :label="1">平台</el-radio>
                        <el-radio :label="2">农场</el-radio>
                    </el-radio-group>
                </div>
            </el-form-item> -->
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="formdata.roleName" placeholder="请输入角色名称" />
      </el-form-item>
      <el-form-item />
    </el-form>
  </c-dialog>
</template>
<script setup>
import { ref, onMounted, reactive } from 'vue'
import { addRole, editRole } from '@/api/system'
import cDialog from '@/components/custom/cDialog.vue'
import { message } from '@/utils/element'
import { ElMessageBox } from 'element-plus'
import companySelect from '@/components/custom/companySelect.vue'
import roleSelect from '@/components/custom/roleSelect.vue'
import { useUserStore } from '@/pinia/modules/user'

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  title: String,
  editData: Object,
  type: Number // 操作类型：1为新增，2为编辑，3为查看
})
const emit = defineEmits(['update:show', 'success'])

const userStore = useUserStore()

const formdata = ref({ roleType: 2 })
const ruleFormRef = ref(null)

// 验证手机号
const checkPhone = (rule, phone, callback) => {
  const myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/
  if (!myreg.test(phone)) {
    return callback(new Error('手机号输入有误'))
  } else {
    callback() // 验证通过
  }
}
const rules = reactive({
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    // { min: 3, max: 50, message: 'Length should be 3 to 5', trigger: 'blur' },
  ]
})

onMounted(() => {
  if (props.editData.id) {
    formdata.value = props.editData
  }
})

const dialogFlag = ref(props.show)

const save = async() => {
  await ruleFormRef.value.validate(async(valid, fields) => {
    if (valid) {
      let res = {}
      if (props.editData.id) {
        res = await editRole(formdata.value)
      } else {
        formdata.value.companyId = userStore.userInfo.companyId
        res = await addRole(formdata.value)
      }
      if (res.code == 0) {
        message('数据提交成功', 2)
        emit('success')
        close()
      } else {
        message(res.message, 3)
      }
    }
  })
}

const close = () => {
  emit('update:show', false)
}
</script>
<style lang="scss" scoped>
    .addBox{
        display: flex;
        height: 40px;
        line-height: 30px;
        .label{
            width: 70px;
        }
    }
</style>
